﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using SimpleFS.Core;

namespace SimpleFS.Services.Transactions.Implementations.Files
{
    public class Write : TransactableOperationTemplate
    {
        internal IFile target;

        internal IFile shadow;

        internal Stream stream;

        public Write(IFile target, Stream stream, IResourceManager resourceManager)
        {
            System.Resources.ResourceManager srm 
                = new System.Resources.ResourceManager(
                "SimpleFS", System.Reflection.Assembly.GetExecutingAssembly());

            if (target == null)
            {
                throw new ArgumentNullException("target", srm.GetString("NullTarget"));
            }
            if (stream == null)
            {
                throw new ArgumentNullException("stream", srm.GetString("NullStream"));
            }

            this.target = target;
            this.stream = stream;
            base.resourceManager = resourceManager;

            this.shadow = this.target.ParentDirectory.GetFile(this.target.Name + ".shadow");
            if (this.shadow != null)
            {
                this.shadow.Delete();
            }
            this.shadow = this.target.ParentDirectory.AddFile(
                this.target.Name + ".shadow");
        }

        protected override void Operate()
        {
            this.shadow.Write(this.stream);
        }

        public override void Commit()
        {
            Console.WriteLine("Commit: {0}", this.target.Name);
            if (this.target.Exists())
            {
                this.target.Delete();
            }
            this.shadow.Rename(this.target.Name);
        }

        public override void Rollback()
        {
            this.shadow.Delete();
        }
    }
}
